<?php


namespace app\admin\controller\wb;


use app\admin\controller\Base;
use app\common\enums\ErrorCode;
use app\common\service\BaseService;
use app\common\utils\RedisUtils;
use app\common\vo\ResultVo;
use app\common\weibo\WeiBoCode;
use SaeTClientV2;
use SaeTOAuthV2;
use OAuthException;
use Exception;
use think\facade\Cookie;
use think\facade\Request;
use think\facade\Session;
use think\route;

class WeiBoController extends Base
{
    public $token = [];
    public $access_token = '';
    public $uid = '';
    public $url = '';

    public function initialize()
    {
        $redis = RedisUtils::init();
        $array = ['callback', 'auth'];
        if (!in_array(Request::action(), $array)) {
            $this->url = Request::url(true);
            $redis->set('redirect_url', Request::url(true));
        }/*
        if ($redis->get('wb_token')){
            $this->token = Session::get('token');
            $this->access_token = Session::get('access_token');
            $this->uid = Session::get('uid');
        }*/
    }

    public function auth()
    {
        try {
            $o = new SaeTOAuthV2(WeiBoCode::WB_AKEY, WeiBoCode::WB_SKEY);
            $code_url = $o->getAuthorizeURL(WeiBoCode::WB_CALLBACK_URL);
            header('Location:' . $code_url);
        } catch (Exception $e) {
            return false;
        } finally {
            $redis = RedisUtils::init();
            redirect($redis->get('redirect_url'));
        }
    }

    /**
     * @route('callbackBase')
     */
    public function callbackBase()
    {
        echo 'test';
        print_r($this->access_token);
    }

    /**
     * @route('callback')
     */
    public function callback()
    {
        $redis = RedisUtils::init();
        $o = new SaeTOAuthV2(WeiBoCode::WB_AKEY, WeiBoCode::WB_SKEY);
        if (isset($_REQUEST['code'])) {
            $keys = array();
            $keys['code'] = $_REQUEST['code'];
            $keys['redirect_uri'] = WeiBoCode::WB_CALLBACK_URL;
            try {
                $token = $o->getAccessToken('code', $keys);
                $redis->set('wb_token', json_encode($token));
                $redis->set('wb_access_token', $token['access_token']);
                $redis->set('wb_uid', $token['uid']);
            } catch (OAuthException $e) {

            }
        }
        if ($redis->get('wb_access_token')) {
            Cookie::set('weibojs_' . $o->client_id, http_build_query(json_decode($redis->get('wb_token'))));
            header('Location:' . $redis->get('redirect_url'));
            return ResultVo::success('身份验证授权成功');
        } else {
            return ResultVo::error(ErrorCode::VALIDATION_FAILED);
        }
    }

    /**
     * @param string $name 微博昵称:default:NULL
     * @route("weibo/list")->allowCrossDomain(); //注释路由的跨域解决方法allowCrossDomain
     * @return string API results
     */
    public function user_timeline_by_name()
    {
        $redis = RedisUtils::init();
        if ($redis->get(date('Y-m-d') . 'wb_list')) {
            return ResultVo::success(json_decode($redis->get(date('Y-m-d') . 'wb_list'), true));
        } else {
            $this->url = Request::url(true);
            $name = $_REQUEST['name'];
            try {
                $WeiBo = $this->BaseWeiBo();
                $result = $WeiBo->user_timeline_by_name($name);
                if (!$result) {
                    return ResultVo::error(ErrorCode::NOT_NETWORK);
                } else {
                    $redis->set(date('Y-m-d') . 'wb_list', json_encode($result), 86400);
                    return ResultVo::success($result);
                }
            } catch (Exception $e) {
                return ResultVo::error(ErrorCode::VALIDATION_FAILED);
            }
        }

        return ResultVo::success($result['statuses']);
    }

    /**
     * @route('weibo/home')->allowCrossDomain();
     * @return \think\response\Json
     */
    public function home_timeline(Request $request)
    {
        try {
            $page =  Request::param('page',1);
            $limit =  Request::param('limit',50);
            $WeiBo = $this->BaseWeiBo();
            $result = $WeiBo->home_timeline($page, $limit);
            if (!$result) {
                return ResultVo::error(ErrorCode::NOT_NETWORK);
            } else {
                return ResultVo::success($result);
            }
        } catch (Exception $e) {
            return ResultVo::error(ErrorCode::VALIDATION_FAILED);
        }

        return ResultVo::success($result['statuses']);

    }

    /**
     * @route('weibo/publish')->allowCrossDomain(); //暂时因本地内网穿透的ip无法通过验证
     * @return \think\response\Json
     * @throws string API results
     */
    public function publish()
    {
        $content = Request::get('content', '测试发布信息');
        try {
            $WeiBo = $this->BaseWeiBo();
            $result = $WeiBo->update($content);
            if (!$result) {
                return ResultVo::error(ErrorCode::NOT_NETWORK);
            } else {
                return ResultVo::success($result);
            }
        } catch (Exception $e) {
            return ResultVo::error(ErrorCode::VALIDATION_FAILED);
        }

        return ResultVo::success($result['statuses']);

    }

    /**
     * 热门微博
     * @route('weibo/hot')->allowCrossDomain();
     * @return bool|string|object
     */
    public function hot()
    {
        try {
            $searchAllUrl = "https://m.weibo.cn/api/container/getIndex?containerid=231583&page_type=searchall";
            $result = BaseService::curl_get($searchAllUrl);
            return $result;
        } catch (Exception $e) {
            return ResultVo::error(ErrorCode::DATA_VALIDATE_FAIL);
        }
    }

    /**
     * 热搜榜
     * @route('weibo/hotSearch')->allowCrossDomain();
     * @return bool|string|object
     */
    public function hot_search()
    {
        try {
            $display_time = time();
            $searchUrl = "https://m.weibo.cn/api/container/getIndex?containerid=106003type%3D25%26t%3D3%26disable_hot%3D1%26filter_type%3Drealtimehot&title=%E5%BE%AE%E5%8D%9A%E7%83%AD%E6%90%9C&extparam=filter_type%3Drealtimehot%26mi_cid%3D100103%26pos%3D0_0%26c_type%3D30%26display_time%3D" . $display_time . "&luicode=10000011&lfid=231583";
            $result = BaseService::curl_get($searchUrl);
            return $result;
        } catch (Exception $e) {
            return ResultVo::error(ErrorCode::DATA_VALIDATE_FAIL);
        }
    }

    /**
     * 热搜词相关
     * @param $desc string 热搜词
     * @param $page string 分页
     * @return bool|string|\think\response\Json
     * @route('weibo/hotDesc')->allowCrossDomain();
     */
    public function hot_desc($desc, $page = null)
    {
        try {
            $time = time();
            $page = $page ? "&page=" . $page : null;
            $descUrl = "https://m.weibo.cn/api/container/getIndex?containerid=100103type%3D1%26t%3D10%26q%3D%23" . $desc . "%23&isnewpage=1&extparam=filter_type%3Drealtimehot%26pos%3D0%26c_type%3D51%26q%3D%23%E8%B0%A2%E9%9C%87%E4%B8%9A%E6%89%93%E7%A0%B4%E4%BA%9A%E6%B4%B2%E7%BA%AA%E5%BD%95%23%26display_time%3D" . $time . "&luicode=10000011&lfid=106003type%3D25%26t%3D3%26disable_hot%3D1%26filter_type%3Drealtimehot&page_type=searchall" . $page;
            $result = BaseService::curl_get($descUrl);
            return $result;
        } catch (Exception $e) {
            return ResultVo::error(ErrorCode::DATA_VALIDATE_FAIL);
        }
    }

    /**
     * 获取微博表情
     * @route('weibo/emotions')->allowCrossDomain();
     * @return \think\response\Json
     */
    public function emotions()
    {
        try {
            $WeiBo = $this->BaseWeiBo();
            $result = $WeiBo->emotions();
            $redis = RedisUtils::init();
            $redis->set('wb_emotions', json_encode($result));
            return ResultVo::success($result);
        } catch (Exception $e) {
            return ResultVo::error(ErrorCode::DATA_VALIDATE_FAIL);
        }
    }

    protected function BaseWeiBo()
    {
        $redis = RedisUtils::init();
        if (empty($redis->get('wb_access_token'))) {
            $this->auth();
        }
        $WeiBo = new SaeTClientV2(WeiBoCode::WB_AKEY, WeiBoCode::WB_SKEY, $redis->get('wb_access_token'));
        return $WeiBo;
    }

}